//
//  MainTabBarViewController.m
//  HengYouCai
//
//  Created by lwj on 2017/4/24.
//  Copyright © 2017年 lwj. All rights reserved.
//

#import "MainTabBarViewController.h"
#import "BaseNavigationController.h"
#import "ZYFinancialContentTypeViewController.h"
#import "HengYouCai-Swift.h"
#import "WLTool.h"
#import <WebKit/WebKit.h>
@interface MainTabBarViewController ()<UITabBarControllerDelegate>

@end

@implementation MainTabBarViewController



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
  
    //添加 蒙版 遮盖
    UIView *shadow = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    shadow.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:shadow];
    NSDictionary *dic = [WLFileManager readUserDataForKey:@"OPENURL"];
    //直接跳转至网页
    if ([dic[@"type"] integerValue] == -1) {
        WKWebViewConfiguration * config = [[WKWebViewConfiguration alloc] init];
        WKWebView *webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds configuration:config];
        webView.backgroundColor = [UIColor whiteColor];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dic[@"link"]]];
        [webView loadRequest:request];
        [self.view addSubview:webView];
        return;
    }else{
        [shadow removeFromSuperview];
    }
    
   
}
- (void)checkVersionUpdate:(NSDictionary*)dic
{
//    [HYCNetService getVersionOnSuccess:^(NSDictionary *dictResult) {
//        //
//        NSDictionary *dic = [NSBundle mainBundle].infoDictionary;
//        NSString *current = dic[@"CFBundleShortVersionString"];
//        NSString *appStore = dictResult[@"version"];
//        NSString *content = dictResult[@"description"];
//        if ([self compareVersionWithCurrentVersion:current appStoreVersion:appStore]) {
//
//            BOOL type = [dictResult[@"type"]  isEqualToString:@"0"];
//            NSString *link = dictResult[@"link"];
//            NSString * wapLink = dictResult[@"wapLink"];
//            BOOL wapStatus = [dictResult[@"wapStatus"] boolValue];
//            [[JCWVerisonUpdateAlertView alloc] initWithVersionCode:appStore updateContent:content canCancel:type updateUrl:link wapLink:wapLink wapStatus:!wapStatus];
//        }
//    } andFailed:^(NSInteger code, NSString *errorMsg) {
//        //
//    }];
            NSDictionary *infoDic = [NSBundle mainBundle].infoDictionary;
            NSString *current = infoDic[@"CFBundleShortVersionString"];
            NSString *appStore = dic[@"version"];
            NSString *content = dic[@"description"];
            NSString *link = dic[@"link"];
            NSInteger type = [dic[@"type"] integerValue];
            if ([self compareVersionWithCurrentVersion:current appStoreVersion:appStore]) {
//                NSString *version = [dic[@"version"] string];
                if (type == 1) { //推荐更新  self.cancleBtn.isHidden = self.canCancel
                    [[JCWVerisonUpdateAlertView alloc]initWithVersionCode:appStore updateContent:content canCancel:false updateUrl:link];
                }else if (type== 0){
                     [[JCWVerisonUpdateAlertView alloc]initWithVersionCode:appStore updateContent:content canCancel:true updateUrl:link];
                }
            }
}
- (BOOL)compareVersionWithCurrentVersion:(NSString *)currentVersion appStoreVersion:(NSString *)appStoreVersion
{
    NSString *currentV = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSString *appStoreV = [appStoreVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    
    
    return currentV.integerValue < appStoreV.integerValue;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate  = self;
    [[UITabBar appearance] setTranslucent:NO];
    // 检测是否登录
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kNotificationNeedLogin object:nil] subscribeNext:^(id x) {
        
        NSString *userToken = [WLFileManager readUserDataForKey:kUserSessionId];
        
        if (userToken.length == 0) {
            
            if (![[MainTabBarViewController obtainTopViewController] isKindOfClass:[JCWLogInVC class]]){
                
                UIViewController *vc = [MainTabBarViewController obtainTopViewController];
                
                [[MainTabBarViewController obtainTopViewController] presentViewController:LogInVC animated:YES completion:^{
                    
                    [vc.navigationController popToRootViewControllerAnimated:NO];
                    UITabBarController *tab = (UITabBarController *)[UIApplication sharedApplication].delegate.window.rootViewController;
                    tab.selectedIndex = 0;
                    
                }];
            }
//            return NO;
        }
//        if (![[UserManager sharedUserManager] checkLogin:self]) return;
    }];


    [self wl_addChildVCWithVCName:NSStringFromClass(HomeTableVC.class),@"首页",@"home2",@"home",nil];
    
//    [self wl_addChildVCWithVCName:NSStringFromClass(ZYFinancialContentTypeViewController.class),@"出借",@"managemoney2",@"managemoney",nil];
    
    [self wl_addChildVCWithVCName:NSStringFromClass(JCWFinancialFroductListVC.class),@"出借",@"managemoney2",@"managemoney",nil];

//    [self addChildVCWithStoryName:@"Financial"
//                            Title:@"理财"
//              withUnSelectedImage:@"managemoney2"
//                withSelectedImage:@"managemoney"];
    
//    [self addChildVCWithStoryName:@"Profile"
//                            Title:@"我的"
//              withUnSelectedImage:@"personage2"
//                withSelectedImage:@"personage"];
    [self wl_addChildVCWithVCName:NSStringFromClass(ZMBMyselfVC.class),@"我的",@"personage2",@"personage",nil];

//    [self wl_addChildVCWithVCName:NSStringFromClass(JCWSafeGuardVC.class),@"更多",@"more2",@"more",nil];
    
    [self wl_addChildVCWithVCName:NSStringFromClass(JCWSafeGuardVC.class),@"更多",@"more2",@"more",nil];


}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSDictionary *dic = [WLFileManager readUserDataForKey:@"OPENURL"];
    [self checkVersionUpdate:dic];
}
//我自己在做参数传递新尝试，可以不用理会
- (void)wl_addChildVCWithVCName:(NSString *)vcName,...{
    NSMutableArray * strArr = [NSMutableArray array];
    if (!vcName.length) {
        return;
    }
    id eachObj;
    va_list argumentList;
    va_start(argumentList, vcName);
    while ((eachObj = va_arg(argumentList, id))) {
        [strArr addObject:eachObj];
    }
    va_end(argumentList);
    Class  className =  NSClassFromString(vcName);
    UIViewController * vc = [className new];
    BaseNavigationController * nav = [[BaseNavigationController alloc] initWithRootViewController:vc];
    if (strArr.count > 2) {
        (void)[vc.tabBarItem initWithTitle:strArr[0] image:[UIImage imageNamed:strArr[1]] selectedImage:[UIImage imageNamed:strArr[2]]];
        [vc.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: UIColorFromRGB(0x666666), NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
        [vc.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: UIColorFromRGB(0xD0B883), NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
    }
    [self addChildViewController:nav];
}

/**
 *  获取当前显示的viewcontroller
 *
 *  @return return 当前显示的vc
 */
+ (UIViewController *)obtainTopViewController{
    return [self obtainTopViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}
+ (UIViewController*)obtainTopViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self obtainTopViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self obtainTopViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self obtainTopViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}
-(void)addChildVCWithStoryName:(NSString *)storyboardName
                         Title:(NSString *)title
           withUnSelectedImage:(NSString *)unSelectedImage
             withSelectedImage:(NSString *)selectedImage
{
    UIImage *normalImg = [UIImage imageNamed:unSelectedImage];
    UIImage *selectedImg = [UIImage imageNamed:selectedImage];
    selectedImg = [selectedImg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    //设置rooViewController
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
    
    UIViewController *rootViewController = mainStoryboard.instantiateInitialViewController;
 
    (void)[rootViewController.tabBarItem  initWithTitle:title image:normalImg selectedImage:selectedImg];
    [rootViewController.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: UIColorFromRGB(0x666666), NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];

    
    [rootViewController.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor redColor], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
    [self addChildViewController:rootViewController];
}
#pragma mark - UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if ([WLFileManager readUserDataForKey:kUserSessionId] == nil &&
        [self.viewControllers indexOfObject:viewController] == 2) {
        [viewController presentViewController:LogInVC animated:true completion:nil];
        return false;
    } else {
        return  true;
    }
}
@end
